﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://www.codeplex.com/EmlenMud
using System.Runtime.Serialization;
using System;
using System.Xml.Serialization;
using System.Threading;
using System.ComponentModel;
#if USE_HYPER
using Hyper.ComponentModel;
#endif

namespace BrainTechLLC.ThreadSafeObjects
{
    /// <summary>
    /// Generic Cache class, used to cache a single item
    /// </summary>
    /// <typeparam name="T"></typeparam>
#if NO_SILVERLIGHT
    [TypeDescriptionProvider(typeof(HyperTypeDescriptionProvider))]
#endif
    [Serializable]
    [DataContract]
    public abstract class GenericCacheBase<T> : GenericCacheAbstractBase<T>, ICacheBase<T>
    {
        [NonSerialized, XmlIgnore]
        protected T _item;

        public GenericCacheBase(TPopulateCacheDelegate<T> populateCacheDelegate) : base(populateCacheDelegate) { }
        public GenericCacheBase(TPopulateCacheDelegateDirect<T> populateCacheDelegate) : base(populateCacheDelegate) { }
        public GenericCacheBase() { }

        /// <summary>
        /// Determines if the cached object is valid/unchanged or invalid/dirty/not retrieved
        /// </summary>	
        public override bool IsCacheValid() { return (_item != null && !_dirty); }

        /// <summary>
        /// Determines if the cached object is valid/unchanged or invalid/dirty/not retrieved, with an optional cache population parameter
        /// </summary>
        public override bool IsCacheValid(object populateCacheParameter) { return (_item != null && !_dirty); }

        /// <summary>
        /// The cached item
        /// </summary>
        public virtual T Item
        {
            get { return (_dirty ? default(T) : _item); }
            set { _item = value; _dirty = false; }
        }
    }
}
